package com.sec.android.app.myfiles.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.activity.AbsMyFilesActivity;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.launch.LaunchMgr;
import com.sec.android.app.myfiles.log.Log;

import java.util.Locale;


public class PermissionDialogFragment extends DialogFragment {
    private static String[] mPermission;
    private View mPermissionDialogView;

    public PermissionDialogFragment() {
        super();
    }

    public static PermissionDialogFragment setArguments(String[] permission) {
        PermissionDialogFragment dialogFragment = new PermissionDialogFragment();
        Bundle bundle = new Bundle();
        dialogFragment.setArguments(bundle);
        mPermission = permission;

        return dialogFragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Activity activity = getActivity();
        initViews(activity);
        setPermissionInfo(activity);
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);
        alertDialog.setView(mPermissionDialogView);
        alertDialog.setPositiveButton(getString(R.string.capital_settings).toUpperCase(Locale.getDefault()), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int keyCode) {
                dismiss();
                try {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + AppConstants.MY_FILES_PACKAGE_NAME));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Activity a = getActivity();
                    if (a != null) {
                        a.finish();
                        startActivity(intent);
                    }
                } catch (ActivityNotFoundException e) {
                    Log.e(this, "ActivityNotFoundException:" + e.toString());
                }
            }
        });
        alertDialog.setNegativeButton(R.string.capital_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int keyCode) {
                dismissAndFinishActivityAffinity();
            }
        });

        setCancelable(false);
        AlertDialog dialog = alertDialog.create();
        dialog.setCanceledOnTouchOutside(false);

        return dialog;
    }

    private void initViews(Context context) {
        LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        mPermissionDialogView = inflate.inflate(R.layout.request_permission_popup, null);
        TextView msgText = (TextView) mPermissionDialogView.findViewById(R.id.request_permission_msg);
        String permissionAppName = context.getResources().getString(R.string.app_name);
        String requestPermissionText = context.getResources().getString(
                R.string.unable_to_open_ps_tap_settings_then_allow_the_following_permissions_and_try_again,
                permissionAppName);
        SpannableStringBuilder sp = new SpannableStringBuilder(requestPermissionText);
        sp.setSpan(new StyleSpan(Typeface.BOLD), requestPermissionText.indexOf(permissionAppName),
                requestPermissionText.indexOf(permissionAppName) + permissionAppName.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        msgText.setText(sp);
    }

    private void setPermissionInfo(Context context) {
        PackageManager packageMgr = context.getPackageManager();
        PermissionGroupInfo permissionGroupInfo = null;
        try {
            PermissionInfo permissionInfo = packageMgr.getPermissionInfo(mPermission[0], PackageManager.GET_META_DATA);
            permissionGroupInfo = packageMgr.getPermissionGroupInfo(permissionInfo.group, PackageManager.GET_META_DATA);

            ImageView permissionImg = (ImageView) mPermissionDialogView.findViewById(R.id.request_permission_rationale_image);
            TextView permissionTxt = (TextView) mPermissionDialogView.findViewById(R.id.request_permission_rationale_text);

            permissionImg.setImageResource(permissionGroupInfo.icon);
            permissionTxt.setText(permissionGroupInfo.loadLabel(packageMgr));
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(this, "PackageManager.NameNotFoundException : " + e);
            dismissAndFinishActivityAffinity();
        }
    }

    @Override
    public void onDestroy() {
        Log.d(this, "onDestroy");
        super.onDestroy();
    }

    @Override
    public void onResume() {
        Log.d(this, "onResume");
        super.onResume();
        AbsMyFilesActivity activity = (AbsMyFilesActivity) getActivity();
        if (isPermissionGranted(activity)) {
            dismiss();
            int processId = activity.getProcessId();
            LaunchMgr.getInstance(processId).handleStart(processId, activity, activity.getIntent());
        }
    }

    private boolean isPermissionGranted(Activity activity){
        boolean result = true;
        for (String permission : mPermission) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                result = false;
                break;
            }
        }
        return result;
    }

    private void dismissAndFinishActivityAffinity() {
        dismiss();
        Activity activity = getActivity();
        if (activity != null) {
            Log.d(this, "dismiss and finish affinity!! All activities having same affinity to MyFiles are terminated now.");
            activity.finishAffinity();
        }
    }
}
